package com.woniuxy.controller;

import com.woniuxy.entity.MUser;
import com.woniuxy.service.FansService;
import com.woniuxy.service.UserService;
import com.woniuxy.util.FindFriends;
import com.woniuxy.util.JwtUtils;
import com.woniuxy.util.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
@Slf4j
@RestController
@Transactional
public class FansController {
    @Autowired
    FansService fansService;

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("fans/searchFans")
    public ResultVo search(@RequestBody String token){
        String loginId = JwtUtils.getLoginId(token);
        List<MUser> mUsers = fansService.searchFans(Integer.valueOf(loginId));
        return ResultVo.success(mUsers);
    }

    @PostMapping("fans/searchFollow")
    public ResultVo searchFollow(@RequestBody String token){
        String loginId = JwtUtils.getLoginId(token);
        List<MUser> mUsers = fansService.searchFollow(Integer.valueOf(loginId));
        return ResultVo.success(mUsers);
    }

    @PostMapping("fans/unFollow")
    public ResultVo unFollow(@RequestBody HashMap<String,Object> map){
        String token = (String) map.remove("token");
        Integer id = (Integer) map.remove("id");
        Integer loginId = Integer.valueOf(JwtUtils.getLoginId(token));
        int i = fansService.unFollow(id, loginId);
        return ResultVo.success("取关成功");
    }

    @PostMapping("fans/findMaybeFriends")
    public ResultVo findMaybeFriends(@RequestBody String token){
        String loginId = JwtUtils.getLoginId(token);
        //获得用户的关注列表
        List<MUser> mFollow = fansService.searchFollow(Integer.valueOf(loginId));
        List<Integer> mFollowsId = new ArrayList<>();
        for (MUser user : mFollow){
            mFollowsId.add(Math.toIntExact(user.getId()));
        }
        //获得关注列表的所有粉丝
        Map<Long, List<Long>> followWithFans = fansService.searchAllUserWithFriends(mFollowsId);
        //计算出共同关注三个以上的用户
        HashSet<Long> allFriends2 = FindFriends.findAllFriends2(followWithFans);
        log.info(allFriends2+"列表");
        if (allFriends2 == null) {
            return ResultVo.success("没有推荐");
        }
        //获得推荐用户的信息响应到前端
        allFriends2.remove(Long.valueOf(loginId));
        List<MUser> users = userService.getSomeUser(allFriends2);
        return ResultVo.success(users);
    }
}
